package com.rent.auth.controller;

import com.rent.auth.pojo.AuthToken;
import com.rent.auth.service.IAdminService;
import com.rent.common.annotation.AvoidRepeatableCommit;
import com.rent.common.api.ApiString;
import com.rent.common.pojo.ResultJSON;
import com.rent.common.utils.StringUtils;
import com.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * @Author zhang
 * @create 2022/3/26 17:07
 */
@Slf4j
@Api(tags = {"刷新token"})
@RestController
@RequestMapping("/refresh")
public class RefreshTokenController {

    @Autowired
    private IAdminService adminService;

    @SysLog(value = "刷新token")
    @AvoidRepeatableCommit(timeout = 3000)
    @RequestMapping(value = "/token", method = RequestMethod.POST)
    @ApiOperation(value = "token过期刷新token,间隔3秒", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "refreshToken", value = "请求的刷新token", dataTypeClass = String.class, required = true, paramType = "query")
    })
    public ResultJSON<AuthToken> refreshToken(@RequestParam String refreshToken) {
        refreshToken = StringUtils.trim(refreshToken);
        if (StringUtils.isEmpty(refreshToken)) return ResultJSON.failure(ApiString.tokenNotNull);
        log.info("刷新token令牌:" + refreshToken);
        AuthToken authToken = adminService.authRefreshToken(refreshToken);
        if (authToken == null) return ResultJSON.failure(ApiString.tokenExpired);
        // 先退出原登录 原token 不再生效
        adminService.logout();
        // 返回刷新成功
        return ResultJSON.success(ApiString.refreshSuccess, authToken);
    }

}
